import { reqCarList, reqDeleteCarById, reqUpdateCheckedById } from "@/api";

const state = {
  carList: [],
};
const mutations = {
  GETCARLIST(state, value) {
    state.carList = value;
  },
};
const actions = {
  async getCarList(context) {
    let result = await reqCarList();
    if (result.code == 200) {
      context.commit("GETCARLIST", result.data);
    }
  },
  async deleteCarListBySkuId(context, skuId) {
    let result = await reqDeleteCarById(skuId);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  async updateCheckedById(context, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("FAIL"));
    }
  },
  deleteAllCheckedCar(context) {
    let promiseAll = [];
    context.getters.carList.cartInfoList.forEach((item) => {
      if (item.isChecked) {
        let promise = context.dispatch("deleteCarListBySkuId", item.skuId);
        promiseAll.push(promise);
      }
    });
    return Promise.all(promiseAll);
  },
  updateAllCarIsChecked(context, isChecked) {
    let promiseAll = [];
    context.state.carList[0].cartInfoList.forEach((item) => {
      let promise = context.dispatch("updateCheckedById", { skuId: item.skuId, isChecked });
      promiseAll.push(promise);
    });
    return Promise.all(promiseAll);
  },
};
const getters = {
  carList(state) {
    return state.carList[0] || {};
  },
};
export default {
  state,
  mutations,
  actions,
  getters,
};
